/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.crm.cs.web.TuangouShopAction
   Module Description   :

   Date Created      : 2011/10/20
   Original Author   : Tina.xu
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.crm.cs.web;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.xwork.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.ec.delivery.entity.ViewDeliveryRule;
import com.yaodian100.ec.delivery.service.DeliveryRuleService;
import com.yaodian100.ec.member.entity.Member;
import com.yaodian100.ec.member.service.AddessService;
import com.yaodian100.ec.member.service.MemberService;
import com.yaodian100.ec.order.entity.Orders;
import com.yaodian100.ec.order.service.OrderService;
import com.yaodian100.ec.product.entity.Product;
import com.yaodian100.ec.product.entity.Specification;
import com.yaodian100.ec.product.service.ProductService;
import com.yaodian100.ec.shopping.entity.CartOrderProduct;
import com.yaodian100.ec.shopping.entity.CartOrderProductDetail;
import com.yaodian100.ec.shopping.entity.CartOrders;
import com.yaodian100.ec.shopping.service.CartOrdersService;

/**
 * @author jeff.ma
 * 
 */
public class TuangouShopAction extends ActionSupport implements Preparable {

	/** serialVersionUID */
	private static final long serialVersionUID = -3322449096753962524L;
	private final Logger logger = LoggerFactory.getLogger(TuangouShopAction.class);
	@Resource
	private MemberService memberService;
	@Resource
	private ProductService productService;
	@Resource
	private CartOrdersService cartService;
	@Resource
	private OrderService orderService;
	@Resource
	private AddessService addressService;
	@Autowired
	private DeliveryRuleService deliveryRuleService;

	// 1: 已选取 member;
	// 2: 确定 member, 选商品中;
	// 3: 确定商品, 填运送地点
	// 4. 告知费用, 选付款方式
	// 5. 显示订单资讯
	private int step = 0;

	private String paymentTp;

	private String function;
	private String memberId;
	private String objId;
	private String chkScm;
	private String cartId;
	private String shipfare;

	private String allowSplit;// 是否允许拆单
	private Member member;
	private CartOrders cart;
	private Orders order;
	private Product product; // for 預購

	private final Map maxShop = new HashMap();
	private final Map<String, Map<String, Specification>> specMap = new HashMap();
	private final Map specInvMap = new HashMap();
	private List<String> specList = new ArrayList();
	private List<String> qtyList = new ArrayList();
	private List<String> amountList = new ArrayList();

	private Map<String, String> provincesMap;// 省份
	private Map<String, String> citysMap;// 城市
	private List<ViewDeliveryRule> districts;
	private boolean canUseCod;// 是否可使用cod付款

	/** default constructor */
	public TuangouShopAction() {
	}

	/**
	 * @return the cart
	 */
	public CartOrders getCart() {
		return cart;
	}

	public String getChkScm() {
		return chkScm;
	}

	/**
	 * @return the function
	 */
	public String getFunction() {
		return function;
	}

	/**
	 * @return the maxShop
	 */
	public Map getMaxShop() {
		return maxShop;
	}

	/**
	 * @return the member
	 */
	public Member getMember() {
		return member;
	}

	/**
	 * @return the memberId
	 */
	public String getMemberId() {
		return memberId;
	}

	/**
	 * @return the objId
	 */
	public String getObjId() {
		return objId;
	}

	/**
	 * @return the order
	 */
	public Orders getOrder() {
		return order;
	}

	/**
	 * @return the paymentTp
	 */
	public String getPaymentTp() {
		return paymentTp;
	}

	/**
	 * @return the product
	 */
	public Product getProduct() {
		return product;
	}

	/**
	 * @return the qryList
	 */
	public List<String> getQtyList() {
		return qtyList;
	}

	/**
	 * @return the specInvMap
	 */
	public Map getSpecInvMap() {
		return specInvMap;
	}

	/**
	 * @return the specList
	 */
	public List<String> getSpecList() {
		return specList;
	}

	/**
	 * @return the specMap
	 */
	public Map getSpecMap() {
		return specMap;
	}

	/**
	 * @return the step
	 */
	public int getStep() {
		return step;
	}

	public String list() {
		return "list";
	}

	public String newShop() {
		member = null;
		cart = null;
		specList = new ArrayList();
		qtyList = new ArrayList();
		amountList = new ArrayList();
		memberId = null;
		chkScm = null;
		return INPUT;
	}

	public String pay() {
		if (update() != INPUT) {
			return INPUT;
		}
		if (member == null) {
			addActionError("会员资料遗失");
			return INPUT;
		}
		if (cart == null) {
			addActionError("购物车资料遗失");
			return INPUT;
		} else {
			if (cart.getCartOrderProducts().size() == 0) {
				addActionError("未挑选商品");
				return INPUT;
			}
		}
		// 是否允许拆单
		if (cart.getCartOrderProducts().size() > 1 && "Y".equals(allowSplit)) {
			cart.setAllowSplit("Y");
		} else {
			cart.setAllowSplit("N");
		}
		Map addonInfo = new HashMap();
		Map payment = new HashMap();
		String remoteAddr = ServletActionContext.getRequest().getRemoteAddr();
		cart.setReceiverEmail(member.getSendEmail());
		addonInfo.put("remoteAddr", remoteAddr);
		addonInfo.put("applySource", "crm");
		payment.put("paymentType", paymentTp);
		if ("02".equals(cart.getInvoiceTp())) {
			payment.put("invotype", cart.getInvoiceTp());
			payment.put("invoTitle", cart.getInvoiceTitle());
		}
		try {
			cart = cartService.save(cart);
			// Map<String, String> optional = new HashMap<String, String>();
			// optional.put("domain", member.getDomainSrc());
			// optional.put("cookie", member.getApplySource());
			// optional.put("memberId", member.getMemberId());
			// cart = cartService.calculateCart(cart, optional);
			if (cart != null) {
				order = orderService.createOrderWithPay(cart, addonInfo, payment);
				order.setMustPay(order.getMustPay().subtract(order.getShipfare()).add(cart.getShipfare()));
				order.setJoinMustPay(order.getJoinMustPay().subtract(order.getShipfare()).add(cart.getShipfare()));
				order.setShipfare(cart.getShipfare());
				order.setProductSum(0);
				order = orderService.get(order.getOrderId());
				if (cart.getCartOrderProducts().get(0).getProdTp().equals("1")) {
					product = productService.get(cart.getCartOrderProducts().get(0).getProdId());
				}
			} else {
				addActionError("购买失败, 购物车编号:" + cart.getCartId());
			}
		} catch (CoreException e) {
			if ("errors.order.amount.zero".equals(e.getMessage())) {
				addActionError("订单金额为零, 无法结帐");
			} else if ("errors.order.address.not.match".equals(e.getMessage())) {
				addActionError("地址不在支援地区, 无法结帐");
			} else {
				addActionError("购买失败, 错误讯息:" + e);
			}
			return INPUT;
		} catch (Exception e) {
			e.printStackTrace();
			addActionError("购买失败, 错误讯息:" + e);
			return INPUT;
		}
		member = null;
		cart = null;
		return "finish";
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.opensymphony.xwork2.Preparable#prepare()
	 */
	@Override
	public void prepare() throws Exception {
		clearErrorsAndMessages();
		if (member == null || cart == null) {
			step = 0;
		}
	}

	/**
	 * @param function the function to set
	 */
	public void setFunction(String function) {
		this.function = function;
	}

	/**
	 * @param memberId the memberId to set
	 */
	public void setMemberId(String memberId) {
		this.memberId = memberId;
	}

	/**
	 * @param objId the objId to set
	 */
	public void setObjId(String objId) {
		this.objId = objId;
	}

	/**
	 * @param paymentTp the paymentTp to set
	 */
	public void setPaymentTp(String paymentTp) {
		this.paymentTp = paymentTp;
	}

	/**
	 * @param qtyList the qtyList to set
	 */
	public void setQtyList(List<String> qtyList) {
		this.qtyList = qtyList;
	}

	/**
	 * @param specList the specList to set
	 */
	public void setSpecList(List<String> specList) {
		this.specList = specList;
	}

	/**
	 * @param step the step to set
	 */
	public void setStep(String step) {
		this.step = Integer.valueOf(step);
	}

	public String update() {
		String result = INPUT;
		String version = "";
		if (member == null) {
			addActionError("会员资料遗失");
			return INPUT;
		}
		if ("add".equals(function) && StringUtils.isNotBlank(objId)) {
			Product p = productService.get(objId);
			if (p != null && p.getProductType() == 6) {
				addActionMessage("N选M商品不提供团购订购, 商品代码: " + objId);
			} else if (p == null || "Y".equals(p.getIsDelete()) || "Q".equals(p.getIsDelete())) {
				addActionMessage("商品已被刪除或不可銷售, 商品代码: " + objId);
			} else {
				try {
					if (null == cart) {
						cart = cartService.createCartForTuangou(member.getMemberId(), objId, null, null, 1, null, null);
						if (cart.getCartId().equals(memberId)) {
							// 若 cartId 與 memberId 相同, 表示這是主購物車, 再建一個
							cart = cartService.createCartForTuangou(member.getMemberId(), objId, null, null, 1, null, null);
						}
						cart.setChannel("crm");
						cart.setChannelSeq(2);
						order = null;
						// wait scm 上線
						chkScm = p.getIsScm();
						shipfare = "0";
						qtyList.add("1");
						amountList.add("0");
					} else {
						if (!StringUtils.equalsIgnoreCase("Y", chkScm) && StringUtils.equalsIgnoreCase("Y", p.getIsScm())) {
							addActionMessage("商品代码: " + objId + " 为转单商品不可以购买，请先结帐后再下单");
						} else {
							cart = cartService.addProductForTuangou(member.getMemberId(), cart, objId, null, 1, null);
							// wait scm 上線
							chkScm = p.getIsScm();
						}
					}
					specMap.put(objId, productService.getSpecifications(objId));
					specInvMap.put(objId, productService.getSpecificationInventoryMap(objId));
					int maxQty = productService.get(objId).getMaxPOQuantity();
					for (CartOrderProduct cop : cart.getCartOrderProducts()) {
						if (objId.equals(cop.getProdId())) {
							maxShop.put(cop.getProdSpecId(), maxQty);
						}
					}
					specList.add(specMap.get(objId).values().iterator().next().getSpecificationId().toString());
				} catch (CoreException e) {
					if ("errors.product.null".equals(e.getMessage())) {
						addActionMessage("商品不存在");
					}
					if ("errors.specification.null".equals(e.getMessage())) {
						addActionMessage("商品规格不存在");
					}
					if ("errors.shelf.null".equals(e.getMessage())) {
						addActionMessage("商品已下架");
					}
					if ("errors.cart.product.type".equals(e.getMessage())) {
						addActionMessage("预购不可合并结帐");
					} else {
						addActionMessage(e.getMessage());
					}
				}
				objId = null;
			}
		} else if ("update".equals(function) || "ajaxupdate".equals(function)) {
			if (StringUtils.isNotBlank(objId) && objId.indexOf(";") != -1) {
				String[] c = StringUtils.split(objId, ";");
				CartOrderProduct cop = cart.getCartOrderProducts().get(Integer.valueOf(c[0]));
				for (int i = 0; i < cop.getDetails().size(); i++) {
					CartOrderProductDetail copd = cop.getDetails().get(i);
					if (i == Integer.valueOf(c[1])) {
						copd.setProdSpecId(specList.get(Integer.valueOf(c[0])));
						copd.setProdSpecName(specMap.get(cop.getProdId()).get(specList.get(Integer.valueOf(c[0])))
								.getSpecificationName());
						if (cop.getProdId().equals(copd.getProdId())) {
							cop.setProdSpecId(specList.get(Integer.valueOf(c[0])));
							cop.setProdSpecName(specMap.get(cop.getProdId()).get(specList.get(Integer.valueOf(c[0])))
									.getSpecificationName());
						}
					}
					copd.setAmount(BigDecimal.valueOf(Double.valueOf(amountList.get(Integer.valueOf(c[0])))));
					// cop.setAmount(BigDecimal.valueOf(Double.valueOf(amountList.get(Integer.valueOf(c[0])))));
					cop.setUnitPrice(BigDecimal.valueOf(Double.valueOf(amountList.get(Integer.valueOf(c[0])))));
					copd.setQty(Integer.valueOf(qtyList.get(Integer.valueOf(c[0]))));
					cop.setQty(Integer.valueOf(qtyList.get(Integer.valueOf(c[0]))));

				}
			}
			if (StringUtils.isNotBlank(shipfare)) {
				cart.setShipfare(BigDecimal.valueOf(Integer.valueOf(shipfare)).setScale(1));
			}
			if ("ajaxupdate".equals(function)) {
				result = "json";
			}
		} else if ("remove".equals(function) && StringUtils.isNotBlank(objId)) {
			if (cart == null) {
				addActionError("购物车资料遗失");
				return INPUT;
			}
			boolean isRemove = false;
			Iterator<CartOrderProduct> it = cart.getCartOrderProducts().iterator();
			int i = 0;
			while (it.hasNext()) {
				CartOrderProduct cop = it.next();
				if (cop.getProdSpecId().equals(objId)) {
					specMap.remove(cop.getProdSpecId());
					specInvMap.remove(cop.getProdSpecId());
					maxShop.remove(cop.getProdSpecId());
					it.remove();
					specList.remove(i);
					qtyList.remove(i);
					amountList.remove(i);
					isRemove = true;
					chkScm = null;
					addActionMessage("移除商品 " + cop.getProdName() + " 成功");
					break;
				}
				i++;
			}
			if (isRemove) {
				cartService.save(cart);
			} else {
				addActionMessage("移除商品  规格代码 " + objId + " 失败");
			}
		} else if ("updAddr".equals(function)) {
		}
		if (null != cart) {
			// 限制COD付款
			canUseCod = deliveryRuleService.chkProdDetailCanUseCod("cart", cart.getCartId());
			// 地址簿-省
			provincesMap = deliveryRuleService.getCartProvinces(cartId);
			if (StringUtils.isNotBlank(cart.getReceiverProvince())) {
				citysMap = deliveryRuleService.getCartCitys(cartId, cart.getReceiverProvince());
				// BigDecimal shipfare = addressService.getFreight(cart.getReceiverProvince(), cart.getWeightSum().multiply(
				// BigDecimal.valueOf(1000)), cart.getAmount().add(cart.getDiscount()));
				// cart.setShipfare(shipfare);
				if (!citysMap.containsKey(cart.getReceiverCity())) {
					cart.setReceiverCity("");
					cart.setReceiverArea("");
					cart.setReceiverAddr("");
				} else {
					if (StringUtils.isNotBlank(cart.getReceiverCity())) {
						districts = deliveryRuleService.getCartDistricts(cartId, cart.getReceiverCity());
						for (ViewDeliveryRule vdr : districts) {
							if (vdr.getToDistrict().equals(cart.getReceiverArea())) {
								cart.setReceiverArea(cart.getReceiverArea());
								version = vdr.getVersion();
								break;
							}
						}
					}
				}
			}
			// Map<String, String> optional = new HashMap<String, String>();
			// optional.put("domain", member.getDomainSrc());
			// optional.put("cookie", member.getApplySource());
			// optional.put("memberId", member.getMemberId());
			// cart = cartService.calculateCart(cart, optional);
			cart.getApplyCampaign().clear();
			for (CartOrderProduct cop : cart.getCartOrderProducts()) {
				cop.getApplyCampaign().clear();
				cop.setDiscount(BigDecimal.ZERO);
			}
			// cart = cartService.save(cart);
			if (StringUtils.isNotBlank(version)) {
				cart.setVersion(version);
			}
			cartId = cart.getCartId();
			function = "";
			objId = "";

		}

		return result;
	}

	public String updateOK() {
		return SUCCESS;
	}

	public String updateMember() {
		if (StringUtils.isNotBlank(memberId)) {
			member = memberService.get(memberId);
			if (member == null || member.getActiveDate() == null) {
				addActionError("会员选取失败, 会员编号 " + memberId + "不存在");
				member = null;
			}
		}
		if (member == null) {
			addActionError("尚未选取会员");
		} else {
			function = null;
		}
		return INPUT;
	}

	public String getCartId() {
		return cartId;
	}

	public void setCartId(String cartId) {
		this.cartId = cartId;
	}

	public Map<String, String> getProvincesMap() {
		return provincesMap;
	}

	public void setProvincesMap(Map<String, String> provincesMap) {
		this.provincesMap = provincesMap;
	}

	public Map<String, String> getCitysMap() {
		return citysMap;
	}

	public void setCitysMap(Map<String, String> citysMap) {
		this.citysMap = citysMap;
	}

	public List<ViewDeliveryRule> getDistricts() {
		return districts;
	}

	public void setDistricts(List<ViewDeliveryRule> districts) {
		this.districts = districts;
	}

	public boolean isCanUseCod() {
		return canUseCod;
	}

	public void setCanUseCod(boolean canUseCod) {
		this.canUseCod = canUseCod;
	}

	public List<String> getAmountList() {
		return amountList;
	}

	public void setAmountList(List<String> amountList) {
		this.amountList = amountList;
	}

	public String getShipfare() {
		return shipfare;
	}

	public void setShipfare(String shipfare) {
		this.shipfare = shipfare;
	}

	public String getAllowSplit() {
		return allowSplit;
	}

	public void setAllowSplit(String allowSplit) {
		this.allowSplit = allowSplit;
	}

}
